import { defineStore } from 'pinia';
import axios from 'axios';

export const useDataStore = defineStore('data', {
  state: () => ({
    jsonData: null,
    lastModified: null
  }),

  actions: {
    // 加载初始数据
    async loadInitialData() {
      try {
        // 检查本地是否有保存的数据
        const savedData = localStorage.getItem('appData');
        const savedTimestamp = localStorage.getItem('dataTimestamp');

        if (savedData && savedTimestamp) {
          this.jsonData = JSON.parse(savedData);
          this.lastModified = savedTimestamp;
        } else {
          // 首次加载获取public目录下的JSON
          const response = await axios.get('/data.json');
          this.jsonData = response.data;
          this.lastModified = new Date().toISOString();
          this.saveToLocal();
        }
      } catch (error) {
        console.error('加载数据失败:', error);
        this.jsonData = { users: [] }; // 失败时使用空数据
      }
    },

    // 更新数据
    updateUser(userId, newData) {
      if (!this.jsonData?.users) return;

      const userIndex = this.jsonData.users.findIndex(u => u.id === userId);
      if (userIndex !== -1) {
        this.jsonData.users[userIndex] = {
          ...this.jsonData.users[userIndex],
          ...newData
        };
        this.lastModified = new Date().toISOString();
        this.saveToLocal();
      }
    },

    // 添加新用户
    addUser(newUser) {
      if (!this.jsonData?.users) this.jsonData = { users: [] };

      const newId = Math.max(0, ...this.jsonData.users.map(u => u.id)) + 1;
      this.jsonData.users.push({
        id: newId,
        ...newUser
      });
      this.lastModified = new Date().toISOString();
      this.saveToLocal();
    },

    // 保存到本地存储
    saveToLocal() {
      localStorage.setItem('appData', JSON.stringify(this.jsonData));
      localStorage.setItem('dataTimestamp', this.lastModified);
    }
  },

  getters: {
    getUserById: (state) => (id) => {
      return state.jsonData?.users?.find(user => user.id === id) || null;
    },
    allUsers: (state) => state.jsonData?.users || []
  }
});